<template>
  <div>
    <div v-show="loading">加载中...</div>
    <div v-show="!loading && !cartList.length">购物车为空！</div>

    <div v-show="!loading">
      <div v-for="(item, index) in cartList" :key="index">
        id：{{ item.goodsId }} 名称：{{ item.goodsName }} 数量：{{
          item.number
        }}
        操作：
        <button @click="handleAddGoods(item)">+</button>
        &nbsp;&nbsp;
        <button @click="handleReduceGoods(item)">-</button>
        &nbsp;&nbsp;
        <button @click="handleRemoveGoods(item)">X</button>
      </div>
    </div>

    <div>
      <br />
      <input
        v-model="goodsForm.goodsName"
        type="text"
        placeholder="请输入名称"
      />
      <br />
      <input
        v-model="goodsForm.number"
        type="number"
        placeholder="请输入数量"
      />
      <br />
      <button @click="handleAddGoods()">添加</button>
    </div>
  </div>
</template>

<script lang="ts">
import * as Vue from "vue";
import { useStore } from "vuex";
import { Goods } from "@/entity/Goods";

export default Vue.defineComponent({
  name: "BySetup",

  setup() {
    const store = useStore();

    const loading = Vue.ref(false);

    // 列表
    const cartList = Vue.computed(() => store.state.cart?.cartList || []);

    // 获取列表
    function getCartList() {
      loading.value = true;
      return store
        .dispatch("cart/getCartList", {
          page: 1,
          limit: 10,
        })
        .finally(() => {
          loading.value = false;
        });
    }

    Vue.onMounted(() => {
      getCartList();
    });

    // 表单
    const goodsForm = Vue.reactive<Goods>({
      goodsId: 0,
      goodsName: "",
      number: 1,
    });

    // 重新设置表单
    function resetGoodsForm() {
      goodsForm.goodsId = 0;
      goodsForm.goodsName = "";
      goodsForm.number = 1;
    }

    // 添加
    function handleAddGoods(_goods?: Goods) {
      const goods = _goods || goodsForm;
      if (!goods.goodsName) {
        alert("请输入商品名称");
      } else if (goods.number < 1) {
        alert("请输入正确的数量");
      } else {
        // 如果没有 id，根据列表生成
        if (!goods.goodsId) {
          goods.goodsId = cartList.value.length + 1;
        }
        store.commit("cart/AddCartList", goods);
      }
      // 重新设置表单
      resetGoodsForm();
    }

    // 减少
    function handleReduceGoods(goods: Goods) {
      store.commit("cart/reduceCartList", goods);
    }

    // 删除
    function handleRemoveGoods(goods: Goods) {
      store.commit("cart/removeCartList", goods);
    }

    return {
      loading,
      cartList,
      goodsForm,
      handleAddGoods,
      handleReduceGoods,
      handleRemoveGoods,
    };
  },
});
</script>
